<template>
  <view class="food-pickup-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="header-title">帮拿外卖</view>
      <view class="header-actions">
        <text class="action-icon">⋯</text>
        <text class="action-icon">−</text>
        <text class="action-icon">◎</text>
      </view>
    </view>

    <!-- 顶部横幅 -->
    <view class="banner">
      <view class="banner-content">
        <text class="banner-title">帮取外卖, 便捷到家</text>
        <text class="ai-generated">AI生成</text>
      </view>
    </view>

    <!-- 任务说明 -->
    <view class="section">
      <view class="section-title">任务说明</view>
      <view class="task-description">
        根据客户所提供说明,进行配送(平台仅支付跑腿费用)
      </view>
    </view>

    <!-- 配送信息 -->
    <view class="section">
      <view class="section-title">配送信息</view>
      
      <!-- 帮忙地址 -->
      <view class="info-row" @click="selectAddress">
        <view class="info-left">
          <view class="info-icon">📍</view>
          <text class="info-label">请选择帮忙地址</text>
        </view>
        <view class="info-right">
          <text class="info-value" :class="{ 'placeholder': !selectedAddress }">
            {{ selectedAddress || '请选择' }}
          </text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <!-- 服务时间 -->
      <view class="info-row" @click="selectServiceTime">
        <view class="info-left">
          <view class="info-icon">🕐</view>
          <text class="info-label">请选择服务时间</text>
        </view>
        <view class="info-right">
          <text class="info-value">{{ serviceTime }}</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>
    </view>

    <!-- 外卖信息描述 -->
    <view class="section">
      <view class="section-title">请在下方描述外卖具体信息</view>
      <view class="description-input-container">
        <textarea 
          class="description-input" 
          v-model="foodDescription" 
          placeholder="请输入需求"
          maxlength="500"
          :show-confirm-bar="false"
        />
        <view class="char-count">{{ foodDescription.length }}/500</view>
      </view>
    </view>

    <!-- 其他选项 -->
    <view class="section">
      <view class="section-title">其他选项</view>
      
      <!-- 物品尺寸 -->
      <view class="info-row" @click="selectItemSize">
        <view class="info-left">
          <view class="info-icon">📦</view>
          <text class="info-label">物品尺寸</text>
        </view>
        <view class="info-right">
          <text class="info-value">{{ itemSize }}</text>
          <text class="arrow-icon">›</text>
        </view>
      </view>
      
      <!-- 小费 -->
      <view class="info-row" @click="selectTip">
        <view class="info-left">
          <view class="info-icon">💰</view>
          <text class="info-label">小费</text>
        </view>
        <view class="info-right">
          <text class="info-value" :class="{ 'placeholder': !tipAmount }">
            {{ tipAmount ? `¥${tipAmount}` : '请输入小费' }}
          </text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <!-- 上传图片 -->
      <view class="info-row" @click="uploadImage">
        <view class="info-left">
          <view class="info-icon">📷</view>
          <text class="info-label">请在此处上传外卖信息图</text>
        </view>
        <view class="info-right">
          <text class="info-value" :class="{ 'placeholder': !uploadedImage }">
            {{ uploadedImage ? '已上传' : '请上传图片' }}
          </text>
          <text class="arrow-icon">›</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="total-amount">
        <text class="amount-label">实际金额: </text>
        <text class="amount-value">¥{{ totalAmount }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder" :disabled="!canSubmit || isSubmitting">
        <text class="submit-text">{{ isSubmitting ? '提交中...' : '确认提交' }}</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { createFoodPickupOrder, uploadFoodImage } from '@/api/food-pickup'
import type { FoodPickupRequest } from '@/types/api/food-pickup'
import { getSizePrice, getTipOptions } from '@/config/pricing'

// 响应式数据
const selectedAddress = ref('')
const serviceTime = ref('今日, 20:00-20:30')
const foodDescription = ref('')
const itemSize = ref('小(美瞳/手机壳)左右')
const tipAmount = ref(0)
const uploadedImage = ref('')
const isSubmitting = ref(false)

// 计算属性
const baseFee = computed(() => {
  return getSizePrice('FOOD_PICKUP', itemSize.value)
})

// 计算属性
const totalAmount = computed(() => {
  return baseFee.value + tipAmount.value
})

const canSubmit = computed(() => {
  return selectedAddress.value && foodDescription.value.trim()
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/address-select/address-select',
    events: {
      addressSelected: (address: string) => {
        selectedAddress.value = address
      }
    }
  })
}

const selectServiceTime = () => {
  const timeOptions = [
    '今日, 20:00-20:30',
    '今日, 20:30-21:00', 
    '今日, 21:00-21:30',
    '明日, 09:00-09:30',
    '明日, 12:00-12:30'
  ]
  
  uni.showActionSheet({
    itemList: timeOptions,
    success: (res) => {
      serviceTime.value = timeOptions[res.tapIndex]
    }
  })
}

const selectItemSize = () => {
  const sizeOptions = ['小(美瞳/手机壳)左右', '中(书本/衣服)左右', '大(行李箱/大件)左右']
  uni.showActionSheet({
    itemList: sizeOptions,
    success: (res) => {
      itemSize.value = sizeOptions[res.tapIndex]
      // 价格会自动更新，因为baseFee是计算属性
    }
  })
}

const selectTip = () => {
  const tipOptions = getTipOptions()
  
  uni.showActionSheet({
    itemList: tipOptions.map(tip => `¥${tip}`),
    success: (res) => {
      tipAmount.value = tipOptions[res.tapIndex]
    }
  })
}

const uploadImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      
      try {
        // 显示上传中提示
        uni.showLoading({
          title: '上传中...'
        })
        
        // 这里可以调用上传API将图片上传到服务器
        // const response = await uploadFoodImage(tempFilePath)
        // if (response.success) {
        //   uploadedImage.value = response.data.imageUrl
        //   uni.showToast({
        //     title: '图片上传成功',
        //     icon: 'success'
        //   })
        // }
        
        // 暂时直接使用本地路径
        uploadedImage.value = tempFilePath
        uni.showToast({
          title: '图片选择成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('图片上传失败:', error)
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  })
}

const submitOrder = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完善必填信息',
      icon: 'none'
    })
    return
  }

  if (isSubmitting.value) return

  try {
    isSubmitting.value = true
    
    // 准备订单数据
    const orderData: FoodPickupRequest = {
      deliveryAddress: selectedAddress.value,
      serviceTime: serviceTime.value,
      foodDescription: foodDescription.value,
      tipAmount: tipAmount.value,
      uploadedImage: uploadedImage.value,
      baseFee: baseFee.value,
      totalAmount: totalAmount.value
    }

    // 调用创建订单API
    const response = await createFoodPickupOrder(orderData)
    
    if (response.success) {
      uni.showToast({
        title: '订单创建成功',
        icon: 'success'
      })
      
      // 跳转到订单确认页面
      uni.navigateTo({
        url: '/pages/order-confirm/order-confirm',
        success: (res) => {
          res.eventChannel.emit('foodPickupData', orderData)
        }
      })
    } else {
      uni.showToast({
        title: response.message || '订单创建失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.food-pickup-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 20rpx;
}

.action-icon {
  font-size: 32rpx;
  color: #666;
}

/* 顶部横幅 */
.banner {
  background: linear-gradient(135deg, #ff6b6b, #ffa726, #ffeb3b, #4caf50);
  padding: 40rpx 30rpx;
  position: relative;
  overflow: hidden;
}

.banner-content {
  text-align: center;
  position: relative;
  z-index: 2;
}

.banner-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.ai-generated {
  font-size: 24rpx;
  color: #666;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

/* 内容区域 */
.section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  border-bottom: 2rpx solid #ff6b6b;
  padding-bottom: 10rpx;
}

.task-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex: 1;
}

.info-icon {
  font-size: 32rpx;
  color: #ff6b6b;
}

.info-label {
  font-size: 30rpx;
  color: #333;
}

.info-right {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  max-width: 300rpx;
  text-align: right;
}

.info-value.placeholder {
  color: #999;
}

.arrow-icon {
  font-size: 24rpx;
  color: #ccc;
}

/* 描述输入框 */
.description-input-container {
  position: relative;
}

.description-input {
  width: 100%;
  min-height: 200rpx;
  background-color: #f8f8f8;
  border-radius: 15rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  box-sizing: border-box;
}

.char-count {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #999;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-amount {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.amount-label {
  font-size: 28rpx;
  color: #333;
}

.amount-value {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.submit-btn {
  background-color: #ff6b6b;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  padding: 20rpx 40rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  background-color: #ccc;
  color: #999;
}

.submit-text {
  font-size: 32rpx;
}
</style>
